import React, { Component } from 'react'
import { View, StyleSheet, Text } from 'react-native'

export default class VerifyCode extends Component {
  constructor (props) {
    super(props)
    this.state = {
      verifyCode: '获取验证码'
    }
    this.time = props.time || 60
  }

  render () {
    return (
      <View style={Object.assign({}, styles.container, this.props.style)}>
        <Text style={styles.verifyCode} onPress={this.getVerifyCode}>{this.state.verifyCode}</Text>
      </View>
    )
  }

  /**
   * 获取验证码
   */
  getVerifyCode () {
    if (this.countDownId) { // 正在获取
      console.info(this.countDownId)
    } else { // 开始获取
      this.setVerifyCode(this.time + '秒后重试')
      this.props.getVerifyCode && this.props.getVerifyCode()
      this.countDownId = setInterval(() => {
        this.time--
        if (this.time <= 0) {
          this.clearCountDown()
          this.setVerifyCode('重新获取')
        } else {
          this.setVerifyCode(this.time + '秒后重试')
        }
      }, 1000)
    }
  }

  clearCountDown () {
    console.info('clearCountDown')
    this.countDownId && clearInterval(this.countDownId)
    this.countDownId = null
    this.time = this.props.time || 60
  }

  setVerifyCode (verifyCode) {
    this.setState({
      verifyCode
    })
  }
}

const styles = StyleSheet.create({
  container: {},
  verifyCode: {}
})
